import argparse
import json
import uuid
from time import time

import peewee as pw
import requests
from wsc_core import models

parser = argparse.ArgumentParser()
parser.add_argument('db', help='Database name')
parser.add_argument(
    'db-info', default='{"user": "postgres", "password": "postgres"}', help='Database connection information'
)
parser.add_argument('course-uuid', help='UUID of Data Structure course')
args = parser.parse_args()
db = pw.PostgresqlDatabase(args.db, **json.loads(args.db_info))
models.Model.Meta.database = db


def save(question, difficulty, knowledge_points, solution_article):
    question = models.Question(question=question, level=difficulty)
    for kp in knowledge_points:
        with db.atomic() as txn:
            if not models.KnowledgePoint.get_or_none(name=kp, deleted=False):
                models.KnowledgePoint.insert({
                    'uuid': str(uuid.uuid4()),
                    'creation_time': int(time()),
                    'name': kp,
                    'course_uuid': args.course_uuid,
                }).execute()
    if solution_article:
        question.analysis = solution_article


headers = {
    'Host': 'leetcode-cn.com',
    'Origin': 'https://leetcode-cn.com',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Language': 'zh-CN,zh-TW;q=0.8,zh-HK;q=0.7,zh;q=0.5,en-US;q=0.3,en;q=0.2',
    'Accept-Encoding': 'gzip, deflate, br',
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
    'DNT': '1',
    'Pragma': 'no-cache',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
}
session = requests.Session()
session.headers.update(headers)

all_questions = session.get('https://leetcode-cn.com/api/problems/all/', headers={
    'Accept': 'application/json, text/javascript, */*; q=0.01',
}).json()['stat_status_pairs']

for question1 in all_questions:
    title = question1['stat']['question__title_slug']
    if question1['paid_only']:
        print(f'{title} needs to be paid')
        continue
    questionData = session.post('https://leetcode-cn.com/graphql/', headers={'Accept': '*/*'}, json={
        'operationName': 'questionData',
        'query': 'query questionData($titleSlug: String!) {\n'
                 '  question(titleSlug: $titleSlug) {\n'
                 '    content\n'
                 '    translatedContent\n'
                 '    topicTags {\n'
                 '      name\n'
                 '      translatedName\n'
                 '    }\n'
                 '  }\n'
                 '}',
        'variables': {'titleSlug': title},
    }).json()['data']['question']
    content = questionData['translatedContent']
    if not content:
        print(f'{title} does not have translation')
        continue
    difficulty1 = question1['difficulty']['level']
    knowledgePoints1 = [
        kp['translatedName'] if kp['translatedName'] else kp['name']
        for kp in questionData['topicTags']
    ]

    questionSolutionArticles = session.post('https://leetcode-cn.com/graphql/', headers={'Accept': '*/*'}, json={
        'operationName': 'questionSolutionArticles',
        'query': 'query questionSolutionArticles($questionSlug: String!, $skip: Int, $first: Int, $orderBy: SolutionArticleOrderBy, $userInput: String, $tagSlugs: [String!]) {\n'
                 '  questionSolutionArticles(questionSlug: $questionSlug, skip: $skip, first: $first, orderBy: $orderBy, userInput: $userInput, tagSlugs: $tagSlugs) {\n'
                 '    edges {\n'
                 '      node {\n'
                 '        ...solutionArticle\n'
                 '      }\n'
                 '    }\n'
                 '  }\n'
                 '}\n'
                 '\n'
                 'fragment solutionArticle on SolutionArticleNode {\n'
                 '  slug\n'
                 '  byLeetcode\n'
                 '}',
        'variables': {
            'first': 5,
            'orderBy': 'DEFAULT',
            'questionSlug': title,
            'skip': 0,
        },
    }).json()['data']['questionSolutionArticles']['edges']
    targetSlug = None
    for solutionArticle1 in questionSolutionArticles:
        if solutionArticle1['node']['byLeetcode']:
            targetSlug = solutionArticle1['node']['slug']
            break
    if not targetSlug:
        print(f'{title} does not have official solution')
        continue
    targetSolutionArticle = session.post('https://leetcode-cn.com/graphql/', headers={'Accept': '*/*'}, json={
        'operationName': 'solutionDetailArticle',
        'query': 'query solutionDetailArticle($slug: String!, $orderBy: SolutionArticleOrderBy!) {'
                 '  solutionArticle(slug: $slug, orderBy: $orderBy) {'
                 '    content'
                 '  }'
                 '}',
        'variables': {
            'orderBy': 'DEFAULT',
            'slug': targetSlug,
        },
    }).json()['data']['solutionArticle']['content']
    print('\n'.join((title, str(difficulty1), str(knowledgePoints1))), end='\n\n')
    # save(content, difficulty1, knowledgePoints1, officialSolutionArticle)
